package com.skivingcloud.report.ureport;

import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import com.skivingcloud.common.exception.BusinessException;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * 给文件加水印及保护
 */
public class PDFAndOfficeWatermark {

    private static int interval = -5;

    public static void main(String[] args) {

        try {
           /* PdfReader reader = new PdfReader("E:\\SVN\\发版上线说明.pdf");
            FileOutputStream outputStream = new FileOutputStream( "E:\\SVN\\水印-发版上线说明.pdf");
            watermark(reader, "20200605路人甲88888888", outputStream, true, "123456");*/
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 给pdf文件添加水印
     * @param reader pdf内容
     * @param waterText 水印文字
     * @param out 输出流
     * @param encryption 是否需要加密
     * @param password 加密密码
     * @throws Exception
     */
    public static void watermark(PdfReader reader, String waterText, OutputStream out, boolean encryption, String password) throws Exception{
        PdfStamper stamper = new PdfStamper(reader, out);

        BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",   BaseFont.EMBEDDED);
        if(encryption){
            if(com.skivingcloud.common.utils.StringUtils.isBlank(password)){
                throw new BusinessException("必须传入密码");
            }
            byte[] ownerPassword = password.getBytes();
            stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_ASSEMBLY, false);
            stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_COPY, false);
            stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_DEGRADED_PRINTING, false);
            stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_FILL_IN, false);
            stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_MODIFY_ANNOTATIONS, false);
            stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_MODIFY_CONTENTS, false);
            stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_SCREENREADERS, false);
            stamper.setEncryption(null, ownerPassword, PdfWriter.DO_NOT_ENCRYPT_METADATA, false);
            stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_PRINTING, true);
            stamper.setViewerPreferences(PdfWriter.HideToolbar|PdfWriter.HideMenubar);
        }

        Rectangle pageRect = null;
        PdfGState gs = new PdfGState();
        gs.setFillOpacity(0.2f);
        gs.setStrokeOpacity(0.3f);
        int total = reader.getNumberOfPages() + 1;

        JLabel label = new JLabel();
        FontMetrics metrics;
        int textH = 0;
        int textW = 0;
        label.setText(waterText);
        metrics = label.getFontMetrics(label.getFont());
        textH = metrics.getHeight();
        textW = metrics.stringWidth(label.getText());
        PdfContentByte under;
        for (int i = 1; i < total; i++) {
            pageRect = reader.getPageSizeWithRotation(i);
            under = stamper.getOverContent(i);
//            under = stamper.getUnderContent(i);
            under.saveState();
            under.setGState(gs);
            under.beginText();
            under.setFontAndSize(base, 12);
            under.setTextMatrix(70, 200);
            // 水印文字成30度角倾斜
            //你可以随心所欲的改你自己想要的角度
            for (int height = interval + textH; height < pageRect.getHeight();
                 height = height + textH*3) {
                for (int width = interval + textW; width < pageRect.getWidth() + textW;
                     width = width + textW) {
                    under.showTextAligned(Element.ALIGN_JUSTIFIED_ALL
                            , waterText, width - textW,
                            height - textH, 30);
                }
            }
            // 添加水印文字
            under.endText();
        }
        //说三遍
        //一定不要忘记关闭流
        //一定不要忘记关闭流
        //一定不要忘记关闭流
        stamper.close();
        reader.close();
    }

    public static void orderPdfToImg(PDDocument doc, String waterText, OutputStream out) throws IOException {
        PDFRenderer renderer = new PDFRenderer(doc);
        /* 第二位参数越大转换后越清晰，相对转换速度越慢 */
        BufferedImage image = renderer.renderImageWithDPI(0, 100);
        BufferedImage img = ImageMarkLogoByIcon.ImageByText(waterText, image, -40);
        ImageIO.write(img,"jpg",out);
    }
}
